﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DatabaseConfiguration.cs" company="CodePlex">
//   Copyright © CodePlex 2012
// </copyright>
// <summary>
//   Class to contain global database configuration options.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DataFramework
{
    using System.Configuration;

    /// <summary>
    /// Class to contain global database configuration options.
    /// </summary>
    public static class DatabaseConfiguration
    {
        /// <summary>
        /// Gets the type of the db.
        /// </summary>
        /// <value>The type of the db.</value>
        internal static DatabaseType DbType { get; private set; }

        /// <summary>
        /// Gets the internal connection string.
        /// </summary>
        /// <value>The internal connection string.</value>
        internal static string InternalConnectionString { get; private set; }

        /// <summary>
        /// Gets a value indicating whether this instance is configured.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is configured; otherwise, <c>false</c>.
        /// </value>
        internal static bool IsConfigured { get; private set; }

        /// <summary>
        /// Configures the global DB options from the application / web configuration file.
        /// </summary>
        public static void Configure()
        {
            var config = (DataFrameworkSection)ConfigurationManager.GetSection("dataFrameworkGroup/dataFramework");

            var connStringKey = config.ConnectionName;

            if (string.IsNullOrEmpty(connStringKey))
            {
                throw new ConfigurationErrorsException("DataFramework connectionKey not set in configuration file");
            }

            var configSetting = ConfigurationManager.ConnectionStrings[connStringKey];

            // Set the config options.
            InternalConnectionString = configSetting.ConnectionString;

            DbType = config.DatabaseType;

            IsConfigured = true;
        }
    }
}
